import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
import {
	getUserInfo,
	getCarCount,
	getkf,
	logout
} from '@/service/api.js'
// 需要永久存储，且下次APP启动需要取出的，在state中的变量名
let saveStateKeys = ['vuex_token', 'curFishery'];

// 保存变量到本地存储中
const saveLifeData = function(key, value) {
	// 判断变量名是否在需要存储的数组中
	if (saveStateKeys.indexOf(key) != -1) {
		// 获取本地存储的lifeData对象，将变量添加到对象中
		let tmp = uni.getStorageSync('lifeData');
		// 第一次打开APP，不存在lifeData变量，故放一个{}空对象
		tmp = tmp ? tmp : {};
		tmp[key] = value;
		// 执行这一步后，所有需要存储的变量，都挂载在本地的lifeData对象中
		uni.setStorageSync('lifeData', tmp);
	}
}

const store = new Vuex.Store({
	state: {
		vuex_token: '',
		StatusBar: 24,
		CustomBar: 60,
		menuBtnWidth: 87,
		themeColor: "#F75451", //默认颜色
		skin: `
			--nav-bg:#F75451;
			--nav-color:#F75451;
			--nav-border-color:#F75451;
		`,
		// 用户信息
		userInfo: {},
		memberId: '',
		isLogin: false, //是否登录
		appName: '花旭',
		openid: '',
		session_key: '',
		unionid: '',
		pid: '', //推荐ID
		cartNum: 0,
		productImgList: [],
		contact: {},
		sysInfo: {},
		shareInfo: {},
		cateId: 0,
		city_info: {},
		kf_info: {},
		currentLocation: uni.getStorageSync('city') || '', //选择城市
		currentProvince: uni.getStorageSync('province') || '', //选择省份
		locationCity: '', //定位城市
		quickOrderInfo: {},
		coupon_deduction: {}, //满减信息
	},
	getters: {
		// 全局配置
		themeColor: state => {
			let theme = state.themeColor;
			if (!theme) {
				theme = '#FF3C47';
			}
			return theme;
		}
	},
	mutations: {
		$uStore(state, payload) {
			console.log('payload', payload)
			// 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
			let nameArr = payload.name.split('.');
			let saveKey = '';
			let len = nameArr.length;
			if (nameArr.length >= 2) {
				let obj = state[nameArr[0]];
				for (let i = 1; i < len - 1; i++) {
					obj = obj[nameArr[i]];
				}
				obj[nameArr[len - 1]] = payload.value;
				saveKey = nameArr[0];
			} else {
				// 单层级变量，在state就是一个普通变量的情况
				state[payload.name] = payload.value;
				saveKey = payload.name;
			}
			// 保存变量到本地，见顶部函数定义
			saveLifeData(saveKey, state[saveKey])
		},
		SET_StatusBar(state, StatusBar) {
			state.StatusBar = StatusBar || 24;
		},
		SET_CustomBar(state, CustomBar) {
			state.CustomBar = CustomBar || 60;
		},
		SET_menuBtnWidth(state, menuBtnWidth) {
			state.menuBtnWidth = menuBtnWidth || 87;
		},
		updateUserInfo(state, userinfo) {
			state.userInfo = userinfo;
			state.memberId = userinfo && userinfo.id ? userinfo.id : ''
		},
		updateIsLogin(state, isLogin) {
			state.isLogin = isLogin;
		},
		SET_PERMSLIST: (state, permslist) => {
			state.permslist = permslist;
		},
		SET_OPENID(state, payload) {
			state.openid = payload.openid;
			state.session_key = payload.session_key;
			state.unionid = payload.unionid;
		},
		setCartNum(state, cartNum) {
			state.cartNum = cartNum;
			uni.setStorageSync('cartNum', cartNum);
			if (!cartNum || parseInt(cartNum, 10) === 0) {
				uni.removeTabBarBadge({
					index: 3
				});
			} else {
				uni.setTabBarBadge({
					index: 3,
					text: cartNum.toString()
				});
			}
		},
		SET_PRODUCTIMGLIST(state, val) {
			state.productImgList = val
		},
		SET_CONTACT(state, val) {
			state.contact = val
		},
		SET_SYSINFO(state, val) {
			console.log('val', val)
			state.sysInfo = val;
			state.appName = val.applet_info.name
		},
		SET_INVITED(state, invited) {
			console.log('invited', invited);
			state.pid = invited;
		},
		SET_SHAREINFO(state, val) {
			console.log('val', val)
			state.shareInfo = val
		},
		SET_CATEID(state, cateId) {
			state.cateId = cateId;
		},
		SET_KfInfo(state, val) {
			console.log('客服信息', val);
			state.kf_info = val.kf_info
			state.city_info = val.city_info
		},
		SET_CURRENTLOCATION(state, val) {
			state.currentLocation = val.city;
			state.currentProvince = val.province;
			uni.setStorageSync('city', val.city || '');
			uni.setStorageSync('province', val.province || '');
			getkf().then(da => {
				console.log('da', da);
				if (da.code == 0) {
					state.kf_info = da.data.kf_info
					state.city_info = da.data.city_info
				}
			})
		},
		SET_LOCATIONCITY(state, val) {
			state.locationCity = val.city;
			uni.setStorageSync('location', val);
		},
		SET_quickOrder(state, val) {
			state.quickOrderInfo = val;
		},
		SET_ShopWxConfig(state, val) {
			state.coupon_deduction = val.coupon_deduction;
		}
	},
	actions: {
		getUserInfo({
			commit,
			dispatch,
			state
		}) {
			return getUserInfo().then(da => {
				console.log('da', da)
				if (da.code == 0) {
					let userInfo = da.data;
					commit('updateUserInfo', userInfo)
					dispatch('getCarCount');
					return userInfo
				}
				return null
			})
		},
		Logout({
			commit,
			state
		}) {
			// logout
			return new Promise((resolve) => {
				logout().then(da => {
					uni.reLaunch({
						url: '/pages/index/index'
					});
				}).finally(() => {
					uni.clearStorage();
					commit('updateUserInfo', false)
					commit('setCartNum', 0)
					commit('updateIsLogin', false)
					//resolve()
				});
			})
		},
		getCarCount({
			commit,
			state
		}) {
			getCarCount().then(response => {
				if (response.code == 0) {
					commit('setCartNum', response.data.cart_number)
				}
			})
		},
	},
	modules: {

	},
})

// 从缓存中取得相同的key进行覆盖操作
let lifeData = uni.getStorageSync('lifeData') || {};
for (let key in lifeData) {
	if (store.state.hasOwnProperty(key)) {
		store.commit('$uStore', {
			name: key,
			value: lifeData[key] || null
		})
	}
}

export default store;